package DataCenter;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashSet;

import DataBasic.*;

public class ConfigModifier extends MetaConfig implements Modifer{

	private static ConfigModifier instance;
	
	private int numOfSubTopics;
	private String keyOfSubTopics;
	private HashSet<String> subTopics;

	private InputStream inputStream;
	
	public static synchronized ConfigModifier sharedInstance() {
		if (instance == null)
			instance = new ConfigModifier();
		
		return instance;
	}

	private ConfigModifier() {
		super();
		
		this.numOfSubTopics = Integer.parseInt(prop.getProperty("numOfSubTopics"));
		this.keyOfSubTopics = prop.getProperty("keyOfSubTopics");
		
		subTopics = ConfigAccessor.sharedInstance().getSubscribedTopicNamesSet();
	}

	/*
	 * modify system configuration
	 */
	
	@Override
	public void beginUpdate() {
		// modify the file in classpath (memory)
		try {
			inputStream = this.getClass().getClassLoader().getResourceAsStream(FILE_NAME);
			this.prop.load(inputStream);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public void endUpdate() {
		try {
			FileOutputStream outStream = new FileOutputStream(FILE_PATH);
			prop.store(outStream, " ");
			outStream.close();
			inputStream.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void updateName(String name) {
		beginUpdate();
		
		ConfigAccessor.sharedInstance().setName(name);
		prop.setProperty("Name", name);
		
		endUpdate();
	}
	
	public void addTheSubscribedTopic(String topicName) {
		String key = findTheEmptyPlaceOfSubTopic();
		prop.setProperty(key, topicName);
		subTopics.add(topicName);
	}
	
	private String findTheEmptyPlaceOfSubTopic() {
		for (int i=1; i<=numOfSubTopics; i++) {
			String key = keyOfSubTopics + String.valueOf(i);
			if (isTheValueOfKeyEmpty(key)) {
				return key; //have found the place and then end loop
			}
		}
		
		return null; //not found
	}
	
	private boolean isTheValueOfKeyEmpty(String key) {
		String value = prop.getProperty(key);
		return value.isEmpty() || value == null;
	}
	
	public void removeTheSubscribedTopic(String topicName) {
		String key = findTheKeyOfWillRemovedSubTopic(topicName);
		prop.setProperty(key, "");
		subTopics.remove(topicName);
	}
	
	private String findTheKeyOfWillRemovedSubTopic(String value) {
		for (int i=1; i<=this.numOfSubTopics; i++) {
			String key = this.keyOfSubTopics + String.valueOf(i);
			if (isTheValueOfKeyEquals(key, value))
				return key;
		}
		return null;
	}
	
	private boolean isTheValueOfKeyEquals(String key, String value) {
		return prop.getProperty(key).equals(value);
	}
	
}
